/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.windesheim.archdemo.view;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.KeyStroke;

/**
 *
 * @author reindert
 */
public abstract class OkCancelDialog extends JDialog {

    private int returnStatus = RET_CANCEL;
    private List<WindowStateListener> listeners;

    public OkCancelDialog(Frame frame, boolean bln) {
        super(frame, bln);

        // Close the dialog when Esc is pressed
        String cancelName = "cancel";
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
        ActionMap actionMap = getRootPane().getActionMap();
        actionMap.put(cancelName, new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                doClose(RET_CANCEL);
            }
        });
    }
    /** A return status code - returned if Cancel button has been pressed */
    public static final int RET_CANCEL = 0;
    /** A return status code - returned if OK button has been pressed */
    public static final int RET_OK = 1;

    /** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
    public int getReturnStatus() {
        return returnStatus;
    }

    protected void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
        doClose(RET_OK);
    }

    protected void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {
        doClose(RET_CANCEL);
    }

    /** Closes the dialog */
    protected void closeDialog(java.awt.event.WindowEvent evt) {
        doClose(RET_CANCEL);
    }

    protected void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
        if (listeners != null) {
            for (WindowStateListener wl : listeners) {
                wl.windowStateChanged(new WindowEvent(this, WindowEvent.WINDOW_CLOSED));
            }
        }
    }

    @Override
    public synchronized void addWindowStateListener(WindowStateListener wl) {
        if (this.listeners == null) {
            this.listeners = new ArrayList<WindowStateListener>();
        }
        this.listeners.add(wl);
    }
}
